package com.sun.study.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Author Sun
 * @Date 2020/4/11 22:16
 * @Version 1.0
 */
public class jdbcUtils_C3P0 {

    //提升作用域
    private  static ComboPooledDataSource dataSource = null;

    static {

        try {
            //如果没有配置文件，则手动设置用户信息和连接数，代码版不建议
          /* dataSource = new ComboPooledDataSource();
           dataSource.setDriverClass("com.mysql.jdbc.driver");
           dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/gradem?useSSL=true&useUnicode=true&characterEncoding=utf8");
           dataSource.setUser("root");
           dataSource.setPassword("s558858118");*/


          //xml文件不用读取，会自动加载
          dataSource = new ComboPooledDataSource();//不写参数，代表使用默认的数据源


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //返回连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    //释放连接
    public static void Release(Connection con, Statement st, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
